import { Button } from 'cc';
import { _decorator, Component, Node } from 'cc';
import EventSystemComponent from './framework/EventSystemComponent.mjs';
import { tween } from 'cc';
import { v3 } from 'cc';
import { SkeletalAnimation } from 'cc';
import { UITransform } from 'cc';
import { Size } from 'cc';
import { view } from 'cc';
import { Camera } from 'cc';
import { find } from 'cc';
import { OrbitFollowTarget } from './framework/OrbitFollowTarget.mjs';
import { EventTouch } from 'cc';
import { Sprite } from 'cc';
import { SpriteFrame } from 'cc';
import { Tween } from 'cc';
import { Layout } from 'cc';
import { instantiate } from 'cc';
import { audioManager } from './framework/WebAudioManager.mjs';
import { UIOpacity } from 'cc';
import { Widget } from 'cc';
import { Label } from 'cc';
import { QtJumpPosition } from './Active';
import { MeshRenderer } from 'cc';
import { Sorting } from 'cc';
import { SortingLayers } from 'cc';
import { AnimationClip } from 'cc';
import { __private } from 'cc';
import { Rect } from 'cc';
import { InstallType, Playable, playable } from './framework/Playable.mjs';
import { gameConfig } from './GameConfig';
const { ccclass, property } = _decorator;
enum AnimState {
    WuXiong = 'wuxiong',
    Handsup = 'handsup',
    Walk = 'walk',
    idle = 'idle',
    DisMAY = 'dismay',
    Panic = 'panic',
    Angry = 'angry',
    Kneel = 'kneel',
    IdleToHandsup = 'idle_to_handsup',
}
enum Audio {
    get = 'sm_get',//获得物品
    load = 'sm_load',//安检屏障下落
    pop = 'sm_pop',//查到物品
    scanning = 'sm_scanning',//查到物品
    voice1 = 'sm_voice1',//走路结束
    voice2 = 'sm_voice2',//生气音频
    walk = 'sm_walk',//走路
    click = 'sm_click',//点击
    switch = 'sm_switch',//镜头放大
    correct = 'sm_correct',//仪器打红圈
    Cry = 'sm_cry',//哭
    WuXiong = 'sm_angry',//捂胸音效
    Scream = 'sm_scream',//刀物品音效
    Frightened = 'sm_frightened',//首个动作
}
@ccclass('GameView')
export class GameView extends EventSystemComponent {
    public static readonly StateChangedEvent = class { constructor(curState: number) { } };
    @property(Camera)
    private TheCamera: Camera = null;
    /**左上角安检图标*/
    @property(Node)
    scan_pattern: Node = null;
    /**安检图标上方遮罩*/
    @property(Node)
    pattern_mask: Node = null;
    /**引导小手部分*/
    @property(Node)
    guide_hand: Node = null;
    /**安检光*/
    @property(Node)
    scanning: Node = null;
    /**等待位置*/
    @property(Node)
    wait_pos: Node = null;
    /**人物节点*/
    @property(Node)
    People: Node = null;
    /**人物节点*/
    @property(Node)
    PosNode: Node = null;
    /**人物角色表情*/
    @property(Node)
    emoje: Node = null;
    /**触摸节点*/
    @property(Node)
    TouchNode: Node = null;
    /**排查节点*/
    @property(Node)
    LoadNode: Node[] = [];
    /**排查节图片*/
    @property(SpriteFrame)
    ResultImg: SpriteFrame[] = [];
    /**排查手节点*/
    @property(SkeletalAnimation)
    MaleHand: SkeletalAnimation = null;
    /**排查出物品的节点*/
    @property(Layout)
    LayoutItem: Layout = null;
    /**逮捕节点*/
    @property(Node)
    btn_arrest: Node = null;
    /**物品背景图片*/
    @property(SpriteFrame)
    thing_bg: SpriteFrame[] = [];
    /**底部跳转节点*/
    @property(Node)
    infoBoard: Node = null;
    /**底部跳转节点*/
    @property(Node)
    ItemFly: Node = null;
    /**物品背景图片*/
    @property(SpriteFrame)
    GoodsItems: SpriteFrame[] = [];

    /**角色Y轴间距*/
    private PeopleZ: number = 1.5
    /**角色列表*/
    private RoleList: Array<string> = ['Female01', 'Female02'];
    /**触摸节点*/
    private LastPos = null;
    /**播放表情状态*/
    private ShowState = {
        Emoje: false,
        WuXiong: false,
        DisMAY: false,
        Kneel: false,
    };
    private items: Array<String> = []
    private TouchStart = false;
    private PatternSize: Size = null;
    private ItemNumArr: Array<number> = [0, 0, 0, 0, 0, 0];
    private CameraPos = {
        start: 84.8,
        enlarge: 82.8,
        endDistanc: 82.2,
        polarAngle: 77.47,
        viewOffsetY: 0
    }
    private TimeStart = false
    private TouchTime = 0
    private AnimPlay = null;
    private StartGamePos = {
        S: v3(-0.04348913043478285, -0.3805298913043473,),
        H: v3(-0.05798550724637698, -0.20657336956521716)
    }
    // 点击屏幕
    private ClickScreen: number = 0
    NodeHaveChild(Node) {

        for (let child of Node.children) {
            if (child.getComponent(MeshRenderer)) {
                let child_Sorting = child.addComponent(Sorting)
                child_Sorting.sortingLayer = SortingLayers.getLayerIndexByName("default");
                child_Sorting.sortingOrder = 0;
                child_Sorting.enabled = true
            }
            if (child.children.length > 0) {
                this.NodeHaveChild(child)
            }
        }
    }
    onLoad() {
        if (!playable.isInduce) {
            this.btn_arrest.getChildByName('text').getComponent(Label).string = 'PLAY NOW';
        }
        this.NodeHaveChild(this.node.getChildByPath('Node/Game'))
        // this.startBtn.node.on('click', this.onStartBtnClick, this);
        // this.endBtn.node.on('click', this.onEndBtnClick, this);
        this.PatternSize = this.scan_pattern.getComponent(UITransform).contentSize.clone()
        this.scheduleOnce(() => {
            this.TheCamera.getComponent(OrbitFollowTarget).radialDistance = this.CameraPos.start
        }, 1)

        this.scheduleOnce(() => {
            this.RoleMove()
        }, 0.7)

        this.node.on(Node.EventType.TOUCH_START, this.onTouchStart, this)
        this.node.on(Node.EventType.TOUCH_MOVE, this.onTouchMove, this)
        this.node.on(Node.EventType.TOUCH_CANCEL, this.onTouchEnd, this)
        this.node.on(Node.EventType.TOUCH_END, this.onTouchEnd, this)
        this.node.on(Node.EventType.TOUCH_END, this.onTouchEnd, this)
        this.node.on(Node.EventType.SIZE_CHANGED, () => {
            this.initSize()
        }, this)

        this.initSize()
        this.schedule(() => {
            if (this.TouchStart && this.TimeStart && !this.ShowState.Kneel) {
                this.TouchTime++
                this.HangZhua += 1
                if (this.HangZhua == 3) {
                    this.HangZhua = 0
                    if (this.TouchStart) {
                        this.MaleHand.play('zhua')
                    }
                    this.scheduleOnce(() => {
                        if (this.TimeStart) {
                            this.MaleHand.stop()
                        }
                    }, 1)
                }
                if (this.TouchTime >= 3 && !this.ShowState.Kneel) {
                    this.guide_hand.active = true;
                    this.HangZhua = 0
                    this.TouchTime = 0

                }

            }
            // 自动播放检查动画
            if (this.PlayScanningState && !this.ShowState.Kneel) {
                this.PlayScanningTime++
                if (this.PlayScanningTime >= 3) {
                    this.PlayScanningState = false;
                    this.PlayScanningTime = 0;
                    this.PlayScanning()
                }
            }

        }, 1)
    }
    private HangZhua = 0
    private H_state = false
    initSize() {
        let view_size = view.getVisibleSize()

        let infoBoardWight: Widget = this.infoBoard.getComponent(Widget);

        let infoBoard_state: boolean = true
        let infoBoard_pos = v3()
        let btn_arrest_bottom: number = 185
        // 安检缩放
        let scan_pattern_scale = 1
        let LayoutItemY = 15
        let H_enlarge = 80.5
        let S_enlarge = 82.8
        let H_start = 82
        let S_start = 84.8
        let polarAngle = 77
        let GameOffsetY = 0
        let GamePos = this.node.getChildByPath('Node/Game').position
        if (view_size.height / view_size.width < 1) {
            this.H_state = true
            infoBoard_state = false
            infoBoardWight.top = 30
            infoBoardWight.left = 30
            btn_arrest_bottom = 30
            scan_pattern_scale = 0.75

            this.LayoutItem.node.setPosition(v3(0, -50, 0))
            this.guide_hand.scale = v3(0.85, 0.85)
            this.guide_hand.getComponent(Widget).bottom = 100;
            this.LayoutItem.getComponent(UITransform).width = view_size.width - (view_size.width / 5)
            this.LayoutItem.spacingX = ((view_size.width - (view_size.width / 5)) - 101 - (136 * 2));
            console.log(this.LayoutItem.spacingX);
            LayoutItemY = 10
            polarAngle = 90
            this.CameraPos.polarAngle = 90
            GameOffsetY = 18.5
            this.CameraPos.viewOffsetY = 17.56

            if (this.CameraPos.enlarge == S_enlarge) {
                this.CameraPos.enlarge = H_enlarge
                this.setTheCameraRadialDistance(this.CameraPos.enlarge)
            }
            this.CameraPos.enlarge = H_enlarge
            // 
            // this.node.getChildByPath('Node/Game').scale = v3(1.1, 1.1, 1)
            // this.guide_hand.setPosition(v3(0, 0))
            this.CameraPos.start = H_start
            // this.TheCamera.rect = new Rect(-0.5, -0.5, 2, 2)
            // if (this.TheCamera.getComponent(OrbitFollowTarget).polarAngle = H_enlarge) {
            //     tween(this.MaleHand.node).to(0.2, { scale: v3(2.5, 2.5, 1.8) }).start()
            // }
            if (GamePos.x == this.StartGamePos.S.x && GamePos.y == this.StartGamePos.S.y) {
                this.node.getChildByPath('Node/Game').setPosition(this.StartGamePos[(this.H_state) ? 'H' : 'S'])
            }

        } else {
            this.H_state = false
            this.CameraPos.polarAngle = 77.47
            this.CameraPos.viewOffsetY = 0
            if (this.CameraPos.enlarge == H_enlarge) {
                this.CameraPos.enlarge = S_enlarge
                this.setTheCameraRadialDistance(this.CameraPos.enlarge)
            }
            this.CameraPos.enlarge = S_enlarge
            this.guide_hand.scale = v3(1, 1)
            this.LayoutItem.node.setPosition(v3(0, 45, 0))
            this.guide_hand.getComponent(Widget).bottom = 280
            this.LayoutItem.getComponent(UITransform).width = view_size.width
            this.LayoutItem.spacingX = (view_size.width - 101 - (136 * 2));
            this.TheCamera.getComponent(OrbitFollowTarget).polarAngle = 77;
            this.CameraPos.start = S_start
            if (GamePos.x == this.StartGamePos.H.x && GamePos.y == this.StartGamePos.H.y) {
                this.node.getChildByPath('Node/Game').setPosition(this.StartGamePos[(this.H_state) ? 'H' : 'S'])
            }
            // this.TheCamera.rect = new Rect(0, 0, 1, 1)
        }
        this.LayoutItem.node.parent.getChildByName('LayoutItemXTest').getComponent(UITransform).width = this.LayoutItem.spacingX
        // if (this.TheCamera.getComponent(OrbitFollowTarget).radialDistance == this.CameraPos.enlarge) {
        //     // 放大
        //     this.MaleHand.node.scale = v3((this.H_state) ? 2.5 : 1.5, (this.H_state) ? 2.5 : 1.5, 1.8)
        // } else {
        //     this.MaleHand.node.scale = v3((this.H_state) ? 2 : 1, (this.H_state) ? 2 : 1, 1.8)
        //     tween(this.MaleHand.node).to(0.2, { scale: v3((this.H_state) ? 2 : 1, (this.H_state) ? 2 : 1, 1.8) }).start()
        // }
        // 最后的摄像机
        // if (this.TheCamera.getComponent(OrbitFollowTarget).radialDistance == this.CameraPos.start - 2) {
        if (this.ShowState.Kneel) {
            this.TheCamera.getComponent(OrbitFollowTarget).polarAngle = this.CameraPos.polarAngle
            this.TheCamera.getComponent(OrbitFollowTarget).viewOffsetY = this.CameraPos.viewOffsetY
            this.TheCamera.getComponent(OrbitFollowTarget).radialDistance = (this.H_state) ? this.CameraPos.start - 1.2 : this.CameraPos.start - 2;
        } else {
            this.TheCamera.getComponent(OrbitFollowTarget).polarAngle = polarAngle
            this.TheCamera.getComponent(OrbitFollowTarget).viewOffsetY = GameOffsetY
        }


        // }

        this.scan_pattern.scale = v3(scan_pattern_scale, scan_pattern_scale, scan_pattern_scale)
        let infoBoardPos = {
            'icon': v3(-250, 0),
            'btn_download': v3(198, 0)
        }
        this.LayoutItem.spacingY = LayoutItemY
        this.btn_arrest.getComponent(Widget).bottom = btn_arrest_bottom;
        this.scan_pattern.getComponent(Widget).left = (!infoBoard_state) ? view_size.width * 0.28 : 50
        if (infoBoard_state) {
            infoBoardWight.bottom = 10
        }
        infoBoardWight.isAlignBottom = infoBoard_state;
        infoBoardWight.isAlignTop = !infoBoard_state
        infoBoardWight.isAlignLeft = !infoBoard_state
        this.infoBoard.getComponent(Layout).enabled = !infoBoard_state;
        let infoBoard_not_show = ['infoBoard', 'star', 'content', 'title']
        for (let child of this.infoBoard.children) {
            if (infoBoard_not_show.indexOf(child.name) >= 0) {
                child.active = infoBoard_state
            } else {
                if (infoBoard_state) {
                    child.setPosition(infoBoardPos[child.name])
                } else {
                    child.setPosition(v3(0, 0))
                }
            }
        }
        infoBoardWight.node.setPosition(v3(0, 0))
        infoBoardWight.bottom = 10
        if (this.H_state) {
            this.infoBoard.getComponent(Layout).updateLayout(this.H_state)
        }

    }

    onTouchStart(event: EventTouch) {
        this.ClickScreen += 1



        this.JumpToState()
        if (this.TouchStart) {
            if (this.ShowState.Kneel) {
                return
            }
            this.TimeStart = false
            if (this.guide_hand.active) {
                this.guide_hand.active = false;
                // this.setTheCameraRadialDistance(this.CameraPos.enlarge)
                // this.infoBoard.active = true
            }
            if (this.TheCamera.getComponent(OrbitFollowTarget).radialDistance == this.CameraPos.start) {
                this.setTheCameraRadialDistance(this.CameraPos.enlarge)
                audioManager.playEffect(Audio.switch)
            }
            this.LastPos = event.getUILocation();
            this.MaleHand.play('zhua')
        }

    }

    setTheCameraRadialDistance(CameraPos) {
        if (this.TouchStart) {

            this.TheCamera.getComponent(OrbitFollowTarget).radialDistance = CameraPos;
            if (CameraPos == this.CameraPos.enlarge) {
                // 放大
                tween(this.MaleHand.node).to(0.2, { scale: v3(2, 2, 1.8) }).start()
            } else {
                tween(this.MaleHand.node).to(0.2, { scale: v3(1.5, 1.5, 1.8) }).start()
                tween(this.node.getChildByPath('Node/Game')).to(0.2, { position: v3(0, 0) }).start()
            }
        }
    }
    onTouchMove(event: EventTouch) {
        if (this.LastPos) {

            if (this.TimeStart) {
                this.TimeStart = false
            }
            if (this.ShowState.Kneel) {
                this.LastPos = null
                return
            }
            let pos = event.getUILocation()
            let newPos = v3(pos.x - this.LastPos.x, pos.y - this.LastPos.y)
            // newPos = this.node.getChildByPath('Node/Game').position.clone()
            let CameraPos = this.node.getChildByPath('Node/Game').position.clone();
            CameraPos.x -= newPos.x / 500
            CameraPos.y -= newPos.y / 500
            this.LastPos = pos
            if (CameraPos.x < -0.3 || CameraPos.x > 0.4 || CameraPos.y < -0.85 || CameraPos.y > 1) return;
            this.node.getChildByPath('Node/Game').setPosition(CameraPos)

        }
    }
    onTouchEnd(event: EventTouch) {
        event.getUILocation();
        this.MaleHand.stop()
        if (this.LoadBar) {
            this.LoadBar = false
            // audioManager.stopAudio(Audio.load)
        }
        if (this.TouchStart) {
            this.TimeStart = true
            this.TouchTime = 0
            this.HangZhua = 0
        }
        this.scheduleOnce(() => {
            for (let i = 0; i <= 3; i++) {
                if (this.ItemNumArr[i] != 1) {
                    this.ItemNumArr[i] = 0
                    if (this.ItemNumArr[i] <= 0) {
                        this.ItemNumArr[i] = 0
                        this.LoadNode[i].getComponent(Sprite).enabled = false;
                        this.LoadNode[i].getChildByName('result').active = true;
                    }
                    this.LoadNode[i].getChildByName('load_img').getComponent(Sprite).fillRange = -this.ItemNumArr[i];
                }
            }
        })
        if (this.AudioLoad) {
            audioManager.stopAudio(this.AudioLoad)
            this.AudioLoad = null
        }

    }
    protected lateUpdate(dt: number): void {
        if (this.TouchStart && !this.TimeStart) {
            this.icon_state()
            // if (this.ShowState.Emoje) {
            //     this.icon_state(true)
            // } else {
            //     this.icon_state()
            // }
        }
    }
    // 排查状态
    icon_state(Last?) {
        if (Last) {
            let p = this.getPos(this.node, this.LoadNode[3])
            let x = p.x + view.getVisibleSize().width / 2
            let y = p.y + view.getVisibleSize().height / 2
            this.serBar(x, y, 3)
        } else {
            let pos = [this.getPos(this.node, this.LoadNode[0]), this.getPos(this.node, this.LoadNode[1]), this.getPos(this.node, this.LoadNode[2]), this.getPos(this.node, this.LoadNode[3]), this.getPos(this.node, this.LoadNode[4]), this.getPos(this.node, this.LoadNode[5])]
            let have = 0
            for (let i in pos) {
                if (this.LoadNode[i].active) {
                    let p = pos[i]
                    let x = p.x + view.getVisibleSize().width / 2
                    let y = p.y + view.getVisibleSize().height / 2
                    if (this.ItemNumArr[i] < 1) {
                        this.serBar(x, y, i)
                    }
                    if (this.ItemNumArr[i] >= 1) {
                        have += 1
                    }
                }

            }

        }
    }
    PlayAnim(name) {
        let node = this.People.getChildByName(this.RoleList[0]);
        if (node) {
            let Anim = node.getComponent(SkeletalAnimation)
            this.AnimPlay = name
            Anim.play(name)

        }
    }
    private LoadBar = false
    private LoadBarState = true
    private AudioLoad: AudioBufferSourceNode = null
    // 设置进度
    serBar(x, y, i) {
        let maxy = 18.48
        let minY = 18.32
        if (this.H_state) {
            minY += 0.3
            maxy += 0.3
        }
        if (x <= 0.06 && x >= -0.02 && y < maxy && y > minY) {
            if (this.ItemNumArr[i] < 1) {
                if (this.ItemNumArr[i] == 0) {
                    this.LoadNode[i].getComponent(Sprite).enabled = true;
                    this.LoadNode[i].getChildByName('result').active = false;
                }
                if (!this.LoadBar) {
                    this.LoadBar = true
                    audioManager.playEffect(Audio.load, true)
                        .then(data => {
                            this.AudioLoad = data
                            if (!this.LoadBarState) {
                                audioManager.stopAudio(data)
                                this.LoadBarState = true
                                this.AudioLoad = null
                            }
                        })
                    // audioManager.playEffect(Audio.get, false)
                    // console.log(audioManager);

                    // this.AudioLoad.play()
                    // audioManager
                }
                this.ItemNumArr[i] += 0.015
                if (this.ItemNumArr[i] >= 1) {
                    this.LastPos = null;
                    this.MaleHand.stop()
                    audioManager.stopAudio(this.AudioLoad)
                    this.AudioLoad = null
                    this.TimeStart = false
                    // this.node.getChildByPath('Node/Game').setPosition(v3(0, 0, 0.2));
                    let state = false
                    if (i == 3) {
                        this.LoadNode[i].getChildByName('result').getComponent(Sprite).spriteFrame = this.ResultImg[1];
                        state = true
                        this.ShowState.Kneel = true;
                        this.MaleHand.node.active = false;
                    }
                    this.ItemNumArr[i] = 1
                    this.LoadNode[i].getChildByName('load_img').getComponent(Sprite).fillRange = -this.ItemNumArr[i];
                    audioManager.playEffect(Audio.get, false)
                    this.ItemShow(state, i)
                    // this.LoadNode[i].getComponent(Sprite).enabled = false;
                    // this.LoadNode[i].getChildByName('result').active = true;
                    this.LoadNode[i].getChildByName('result').scale = v3(1.3, 1.3, 1.3)
                    // this.LoadNode[i].getChildByName('load_img').active = false
                } else {
                    this.LoadNode[i].getChildByName('load_img').getComponent(Sprite).fillRange = -this.ItemNumArr[i];
                }
            }
        } else {
            if (this.ItemNumArr[i] != 1 && this.ItemNumArr[i] != 0) {
                this.ItemNumArr[i] = 0
                this.LoadBar = false
                if (this.ItemNumArr[i] <= 0) {

                    if (!this.AudioLoad) {
                        this.LoadBarState = false
                    } else {
                        audioManager.stopAudio(this.AudioLoad)
                        this.AudioLoad = null
                    }
                    this.ItemNumArr[i] = 0
                    this.LoadNode[i].getComponent(Sprite).enabled = false;
                    this.LoadNode[i].getChildByName('result').active = true;
                }
                this.LoadNode[i].getChildByName('load_img').getComponent(Sprite).fillRange = -this.ItemNumArr[i];
            }


        }
    }
    // 显示搜查物品
    ItemShow(state, i) {
        let goods = ['Pizza', 'Nipple', 'Lipstick', 'Knife', 'Necklace', 'Ring']
        let have = []
        // for (let k of goods) {
        //     if (this.items.indexOf(k) < 0) {
        //         have.push(k)
        //     }
        // }
        let name = goods[i]
        // Math.floor(Math.random() * have.length)
        // this.ItemFly.getComponent(UIOpacity).opacity = 255
        let key = (state) ? 'Knife' : name;
        this.items.push(key)
        let node = this.setItem(key, state, i)
        this.ItemFly.getComponent(Sprite).spriteFrame = this.getItem(key)
        this.LoadNode[i].parent.position.clone()
        this.ItemFly.setPosition(v3(0, 0, 0))
        this.ItemFly.active = true
        this.ItemFly.scale = v3(0, 0, 0)
        tween(this.LoadNode[i]).to(0.3, { scale: v3(0, 0, 0) }).call(() => {
            this.LoadNode[i].active = false
            tween(this.ItemFly).to(0.3, { scale: v3(1.3, 1.3, 1) }, { easing: 'backOut' }).call(() => {
                let pos = this.getPos(this.node, node)
                this.scheduleOnce(() => {
                    this.JumpPos(this.ItemFly, pos, pos.y + 50, 1, 0.25, () => {
                        this.setTheCameraRadialDistance(this.CameraPos.start)
                        this.showUIItem(node, state, key)
                        this.LoadState(false)
                        let have = 0
                        for (let pro of this.ItemNumArr) {
                            if (pro == 1) {
                                have += 1
                            }
                        }
                        // if (have != Number(gameConfig.config1) - 1) {
                        if (have == 1) {
                            this.scheduleOnce(() => {
                                this.PlayAnim(AnimState.DisMAY)
                            })
                            audioManager.playEffect(Audio.Frightened, false)
                        } if (have == 2 || have == 4) {
                            // !this.ShowState.WuXiong
                            // this.ShowState.WuXiong = true;
                            this.scheduleOnce(() => {
                                this.PlayAnim(AnimState.WuXiong)
                                audioManager.playEffect(Audio.WuXiong, false)
                            })

                        } else if (have == 3 || have == 5) {
                            // && !this.ShowState.Emoje
                            this.ShowEmoje()
                            // this.ShowState.Emoje = true
                        } else if (have == 6) {
                            this.scheduleOnce(() => {
                                this.PlayAnim(AnimState.Panic);
                                this.AnimPlay = AnimState.Panic
                            })
                            audioManager.playEffect(Audio.Scream, false)
                        }
                        if (Number(i) == 3) {
                            this.on_arrest()
                            playable.sendAction(5)
                        }else{
                            if(have == 1||have == 3||have == 5){
                                let setAction = 2
                                if(have == 3){
                                    setAction = 3
                                }else if(have == 5){
                                    setAction = 4
                                }
                                playable.sendAction(setAction)
                            }
                        }
                        
                    })
                    // tween(this.ItemFly).to(0.25, { position: pos }).start()
                    tween(this.ItemFly).to(0.25, { scale: v3(0, 0, 0) }).start()
                }, 0.3)
            }).start()
        }).start()

        this.nowShouLoad[i] = false;
    }
    showUIItem(node, state, name) {
        tween(node).to(0.15, { scale: v3(1.1, 1.1, 1) }, { easing: 'backOut' }).to(0.1, { scale: v3(1, 1, 1) }, { easing: 'backOut' }).call(() => {
            // this.node.getChildByPath('Node/Game').setPosition(v3(0, 0))
            if (!state) {
                if (this.TouchStart) {
                    this.TimeStart = true
                    this.TouchTime = 0
                }
            }
            let have_Count = 0
            for (let i = 0; i <= this.ItemNumArr.length; i++) {
                if (!this.LoadNode[3].active && !this.nowShouLoad[3]) {
                    if (this.ItemNumArr[i] == 1) {
                        have_Count += 1
                        if (have_Count == Number(gameConfig.config1) - 1) {
                            this.PlayScanningTime = 0
                            Tween.stopAllByTarget(this.scanning)
                            this.PlayScanning(4)
                            return
                        }
                    }
                }

            }
        }).start()

    }
    JumpPos(node, pos, jumpH, count, time, back?) {
        let tw = QtJumpPosition(node, pos, jumpH, count, time);
        tw.call(() => {
            (back) && back()
        }).start();
    }
    // 设置物品
    setItem(name, state, k) {
        let i = this.LayoutItem.node.children.length
        let node = this.LayoutItem.node.children[i]
        if (!node) {
            node = instantiate(this.LayoutItem.node.children[0])
            this.LayoutItem.node.addChild(node)
        }
        let Pic = node.getChildByName('Sprite')
        Pic.getComponent(Sprite).spriteFrame = this.getItem(name + '_item')
        let sprite_size = Pic.getComponent(UITransform).contentSize
        let scale = 1
        if (sprite_size.width > sprite_size.height) {
            scale = 100 / sprite_size.width
        } else {
            scale = 100 / sprite_size.height
        }
        Pic.scale = v3(scale, scale)
        node.active = true
        node.scale = v3(0, 0, 0)
        tween(node).to(0.25, { scale: v3(1, 1, 1) }, { easing: 'backOut' }).start()
        node.getComponent(Sprite).spriteFrame = this.thing_bg[(state) ? 1 : 0];
        // node.getChildByName('text').getComponent('LocalizeLabel')['localizeKey'] = name
        node.getChildByName('text').getComponent(Label).string = name
        let red_ok = this.scan_pattern.getChildByName('red_ok')
        let red_ok_i = red_ok.children[i];
        if (!red_ok_i) {
            red_ok_i = instantiate(red_ok.children[0])
            red_ok.addChild(red_ok_i)
        }
        red_ok_i.scale = v3(1.3, 1.3, 1.3);
        let pos = this.LoadNode[k].position.clone();
        pos.x *= 100;
        pos.y *= 100;
        red_ok_i.setPosition(pos);
        audioManager.playEffect(Audio.correct, false)

        tween(red_ok_i).to(0.3, { scale: v3(1, 1, 1) }, { easing: 'backOut' }).start()

        return node

    }
    /**进度条状态更新*/
    LoadState(state) {
        if (this.ShowState.Kneel) {
            state = false
        }
        for (let k in this.nowShouLoad) {
            if (this.ItemNumArr[k] < 1) {
                if (state) {
                    if (this.nowShouLoad[k]) {
                        this.LoadNode[k].active = state
                    }
                } else {
                    this.LoadNode[k].active = state
                }
            }
        }
    }
    /**获取物品*/
    getItem(name) {
        let goods = ['Nipple', 'Pizza', 'Lipstick', 'Knife', 'Nipple_item', 'Pizza_item', 'Lipstick_item', 'Knife_item', 'Necklace', 'Necklace_item', 'Ring', 'Ring_item']
        let idx = goods.indexOf(name);
        return this.GoodsItems[idx]
    }
    /**角色移动*/
    RoleMove() {
        this.items = []
        this.ItemNumArr = [0, 0, 0, 0, 0, 0]
        for (let i in this.ItemNumArr) {
            this.LoadNode[i].getComponent(Sprite).enabled = false;
            this.LoadNode[i].getChildByName('result').getComponent(Sprite).spriteFrame = this.ResultImg[0]
            this.LoadNode[i].active = false
        }
        audioManager.playEffect(Audio.walk, false)
        for (let i in this.RoleList) {
            let num_i = Number(i)
            this.scheduleOnce(() => {
                let k = this.RoleList[i]
                let node = this.People.getChildByName(k);

                if (node) {
                    let selfZ = node.positionZ
                    let Anim = node.getComponent(SkeletalAnimation)
                    this.LoadState(false)
                    this.scheduleOnce(() => {
                        Anim.play(AnimState.Walk)
                        this.AnimPlay = AnimState.Walk;
                    })
                    tween(node).to(0.8, { position: v3(0, 0, selfZ + this.PeopleZ) }).call(() => {
                        let play_anim = 'idle'
                        if (num_i == 0) {
                            play_anim = AnimState.IdleToHandsup
                            // this.PlayScanning(3)
                            let state = Anim.getState(AnimState.IdleToHandsup);
                            state.wrapMode = AnimationClip.WrapMode.Normal;
                            this.AnimPlay = play_anim
                        }
                        Anim.play(play_anim)
                        if (num_i == this.RoleList.length - 1) {
                            this.scheduleOnce(() => {
                                this.PlayScanning(3)

                            }, 0.5)
                            audioManager.playEffect(Audio.voice1, false)
                        }
                    }).start()
                }
            }, num_i * 0.5)
        }

        let node = this.People.getChildByName(this.RoleList[0]);
        let Anim = node.getComponent(SkeletalAnimation);
        // Anim.on(__private._cocos_animation_animation_state__EventType.FINISHED,()=>{
        //     console.log(this.AnimPlay);
        // })
        Anim.on(SkeletalAnimation.EventType.PLAY, () => {
            let state = Anim.getState(this.AnimPlay);
            if (this.AnimPlay != AnimState.idle && this.AnimPlay != AnimState.Walk && this.AnimPlay != AnimState.Handsup && this.AnimPlay != AnimState.Panic && this.AnimPlay != AnimState.Kneel) {
                state.wrapMode = AnimationClip.WrapMode.Normal;
            } else {
                state.wrapMode = AnimationClip.WrapMode.Loop;
            }
            state.speed = (this.AnimPlay == AnimState.Angry || this.AnimPlay == AnimState.WuXiong) ? 0.75 : 1;
            // this.AnimPlay 
            // .play(
        })


        Anim.on(SkeletalAnimation.EventType.FINISHED, () => {
            // 抬手过渡动画
            if (this.AnimPlay == AnimState.IdleToHandsup) {
                Anim.play(AnimState.Handsup)
                this.LoadState(true)
            } else {
                if (this.AnimPlay == AnimState.DisMAY || this.AnimPlay == AnimState.WuXiong || this.AnimPlay == AnimState.Angry) {
                    if (!this.ShowState.Kneel) {
                        Anim.play(AnimState.IdleToHandsup)
                        this.AnimPlay = AnimState.IdleToHandsup
                    }
                    if (this.AnimPlay == AnimState.WuXiong || this.AnimPlay == AnimState.Angry) {
                        this.TouchStart = true;
                        this.TimeStart = false;
                    }
                }
            }
            // this.AnimPlay 
            // .play(
        })
        // Anim.hasEventListener
        // this.AnimPlay = AnimState.Walk;

    }
    private nowShouLoad = { 0: false, 1: false, 2: false, 3: false, 4: false, 5: false }
    private PlayScanningState: boolean = false
    private PlayScanningTime: number = 0
    PlayScanning(num?) {
        if (this.ShowState.Kneel) {
            this.PlayScanningState = false;
            return
        }
        this.PlayScanningState = false;
        if (!num) {
            let have_Count = 0
            for (let i = 0; i <= 2; i++) {
                if (!this.LoadNode[3].active && !this.nowShouLoad[3]) {
                    if (!this.nowShouLoad[i].active && this.ItemNumArr[i] == 1) {
                        have_Count += 1
                        if (have_Count == Number(gameConfig.config1) - 1) {
                            this.PlayScanning(4)
                            return
                        }
                    }
                }
            }
            // console.log(have_Count,this.ItemNumArr,this.LoadNode[3].active,this.nowShouLoad);
        }
        this.pattern_mask.active = true;
        this.pattern_mask.getComponent(UITransform).setContentSize(this.PatternSize)
        this.scan_pattern.active = true
        this.scanning.setPosition(v3(0, 2.5, 0))

        let time = 0.8
        let pos_arr = [0, 1, 2, 4, 5]
        // this.getRandomNumbers((num == 4) ? 1 : num)
        // this.scanning.getComponent(UIOpacity).opacity = 0
        if (num) {
            if (num == 4) {
                // Anim.play(AnimState.Handsup)
                this.LoadState(false)

                // this.scheduleOnce(() => {
                //     this.LoadState(false)
                //     this.PlayAnim(AnimState.Handsup)
                // }, 1.5)
                this.nowShouLoad[3] = true

                // for (let i = 0; i <= 2; i++) {
                //     this.LoadNode[i].active = false
                // }
                let k = 3
                let PosNode = this.PosNode.getChildByName('pos' + k)
                let node = this.LoadNode[3]
                node.scale = v3(0.001 * 1.4, 0.001 * 1.4, 1)
                // node.parent = PosNode
                // node.setPosition(v3(0, 0))
                let show_time = Number(k) * 0.3
                this.scheduleOnce(() => {
                    node.active = true;
                    this.LoadState(true)
                    // tween(node.getChildByName('result')).repeatForever(tween(node).to(0.4, { scale: v3(1.12, 1.12) }).to(0.4, { scale: v3(1, 1) })).start();
                    node.getChildByName('result').getComponent(Sprite).spriteFrame = this.ResultImg[1]
                }, show_time + 0.1)

                audioManager.playEffect(Audio.pop, false)
            } else {
                console.log(gameConfig.config1);
                if (Number(gameConfig.config1) == 1) {
                    pos_arr = [0, 1, 2, 3, 4, 5]
                }
                for (let i in pos_arr) {
                    let k = pos_arr[i]
                    let PosNode = this.PosNode.getChildByName('pos' + k)
                    let node = this.LoadNode[k]
                    // node.parent = PosNode
                    // node.setPosition(v3(0, 0))
                    let show_time = Number(k) * 0.12
                    if (k >= 3) {
                        show_time = Number(k - 3) * 0.12
                    }
                    if(k == 3){
                        node.getChildByName('result').getComponent(Sprite).spriteFrame = this.ResultImg[1]
                    }
                    audioManager.playEffect(Audio.pop, false)
                    this.scheduleOnce(() => {
                        node.active = true;
                        this.nowShouLoad[k] = true
                        // tween(node.getChildByName('result')).repeatForever(tween(node).to(0.4, { scale: v3(1.12, 1.12) }).to(0.4, { scale: v3(1, 1) })).start();
                    }, show_time + 0.4)
                    // pos.x * this.TheCamera.orthoHeight
                    // pos.y * this.TheCamera.orthoHeight
                }
            }
        }
        // tween(this.scanning.getComponent(UIOpacity)).to(0.3,{opacity:255}).start()
        tween(this.pattern_mask.getComponent(UITransform)).to(time, { contentSize: new Size(this.PatternSize.width, 0) }).call(() => {
            let have_Count = 0
            // for (let i = 0; i <= 2; i++) {
            //     if (!this.LoadNode[3].active && !this.nowShouLoad[3]) {
            //         if (!this.nowShouLoad[i] && this.ItemNumArr[i] == 1) {
            //             have_Count += 1
            //             if(have_Count == Number(gameConfig.config1)-1){
            //                 this.PlayScanning(4)
            //                 return
            //             }
            //         }
            //     }
            // }
            if (!this.ShowState.Kneel) {
                this.PlayScanningTime = 0;
                this.PlayScanningState = true;
                return
            }
        }).start()
        if (num == 3) {
            this.scanning.active = true;
            audioManager.playEffect(Audio.scanning, false)
            tween(this.scanning).to(time, { positionY: -1 }).call(() => {
                this.scanning.active = false;
                if (num) {
                    if (num == 3) {
                        this.TouchStart = true
                        this.MaleHand.node.active = true
                        this.guide_hand.active = true;
                        this.TimeStart = true
                        this.MaleHand.play('zhua')
                        this.scheduleOnce(() => {
                            if (this.TimeStart) {
                                this.MaleHand.stop()
                            }
                        }, 1)
                        this.scheduleOnce(() => {
                            this.setTheCameraRadialDistance(this.CameraPos.enlarge)
                            tween(this.node.getChildByPath('Node/Game')).to(0.2, { position: this.StartGamePos[(this.H_state) ? 'H' : 'S'] }).start()
                        }, 0.2)
                    } else {
                        this.TimeStart = true
                        this.TouchTime = 0
                        this.TouchStart = true
                    }

                }
                // this.scan_pattern.active = false

            }).start()
        } else {
            this.scanning.active = false;
        }


        // let pos = this.getPos(this.node, this.node.getChildByPath('Node/Game/emoje'))
        // console.log(pos);
        // this.emoje.setPosition(pos)
        // this.emoje.active = true;
    }
    // 逮捕
    on_arrest() {
        this.TimeStart = false
        this.ShowState.Kneel = true;
        this.PlayScanningState = false;
        this.LoadNode[3].active = false
        // this.scan_pattern.active = false
        this.scanning.active = false;
        this.guide_hand.active = false;
        this.LoadState(false)
        this.btn_arrest.active = true;
        this.btn_arrest.scale = v3(0, 0, 1)
        this.scheduleOnce(() => {
            this.LoadState(false)
            this.scheduleOnce(() => {
                this.PlayAnim(AnimState.Kneel);
                audioManager.playEffect(Audio.Cry, false)
                tween(this.btn_arrest).to(0.25, { scale: v3(1, 1, 1) }, { easing: 'backOut' }).call(() => {
                    let gf_hand = this.btn_arrest.getChildByName('gf_hand')
                    gf_hand.active = true
                    tween(gf_hand.getComponent(UIOpacity)).to(0.3, { opacity: 255 }).start()
                    tween(gf_hand).repeatForever(tween(gf_hand).to(0.3, { position: v3(185, 47) }).to(0.3, { position: v3(240, 97) })).start();
                    tween(this.btn_arrest).repeatForever(tween(this.btn_arrest).to(0.3, { scale: v3(1.1, 1.1, 1) }).to(0.3, { scale: v3(1, 1, 1) })).start();
                }).start();
            })

            tween(this.TheCamera).to(0.3, { rect: new Rect(0, 0, 1, 1) }).start()
            // this.btn_arrest.active = false;
            this.TheCamera.getComponent(OrbitFollowTarget).radialDistance = (this.H_state) ? this.CameraPos.start - 1.2 : this.CameraPos.start - 2;
            // this.TheCamera.getComponent(OrbitFollowTarget).polarAngle = 
            // this.TheCamera.getComponent(OrbitFollowTarget).viewOffsetY = 
            // "linear" | "smooth" | "fade" | "constant" | "quadIn" | "quadOut" | "quadInOut" | "quadOutIn" | "cubicIn" | "cubicOut" | "cubicInOut" | "cubicOutIn" | "quartIn" | "quartOut" | "quartInOut" | "quartOutIn" | "quintIn" | "quintOut" | "quintInOut" | "quintOutIn" | "sineIn" | "sineOut" | "sineInOut" | "sineOutIn" | "expoIn" | "expoOut" | "expoInOut" | "expoOutIn" | "circIn" | "circOut" | "circInOut" | "circOutIn" | "elasticIn" | "elasticOut" | "elasticInOut" | "elasticOutIn" | "backIn" | "backOut" | "backInOut" | "backOutIn" | "bounceIn" | "bounceOut" | "bounceInOut" | "bounceOutIn"
            tween(this.TheCamera.getComponent(OrbitFollowTarget)).to(0.5, { polarAngle: this.CameraPos.polarAngle, viewOffsetY: this.CameraPos.viewOffsetY }, { easing: 'smooth' }).start()
        }, 1)
    }
    ShowEmoje() {
        let angle_time = 0.08;
        let node = this.People.getChildByName(this.RoleList[0]);
        let Anim = null
        if (node) {
            Anim = node.getComponent(SkeletalAnimation)
            this.LoadState(false)
            this.scheduleOnce(() => {
                Anim.play(AnimState.Angry)
                this.AnimPlay = AnimState.Angry;
            })

            audioManager.playEffect(Audio.voice2, false)
        }

        this.emoje.active = true
        tween(this.emoje).by(angle_time, { angle: -5 }).by(angle_time, { angle: 5 }).by(angle_time, { angle: 5 }).by(angle_time, { angle: -5 }).by(angle_time, { angle: -5 }).by(angle_time, { angle: 5 }).by(angle_time, { angle: 5 }).by(angle_time, { angle: -5 }).call(() => {
            this.emoje.active = false
        }).start()
    }
    /**获得1-6随机三个数*/
    getRandomNumbers(num) {
        const numbers = [];
        while (numbers.length < num) {
            const num = Math.floor(Math.random() * 6) + 1;
            if (!numbers.includes(num)) {
                numbers.push(num);
            }
        }
        return numbers;
    }
    /**获得位置*/
    getPos(node, child) {
        let pos = node.getComponent(UITransform).convertToNodeSpaceAR(child.parent.getComponent(UITransform).convertToWorldSpaceAR(child.position))
        return pos
    }
    getCameraPos(pos) {
        let cameraNode = find("Main Camera");
        let camera = cameraNode.getComponent(Camera);
        let pointInCameraB = camera.worldToScreen(pos);
        return pointInCameraB
    }
    onStartBtnClick(btn: Button) {
        // 切换到游戏场景
        console.log("onStartBtnClick");
        this.eventSystem.dispatch(GameView.StateChangedEvent, 1);

    }
    onEndBtnClick(btn: Button) {
        // 切换到结束场景
        console.log("onEndBtnClick");
        this.eventSystem.dispatch(GameView.StateChangedEvent, 2);
    }
    private ClickState = false
    onTouchButton(event: Event) {
        let target: any = event.target
        audioManager.playEffect(Audio.click, false)
        if (target.name == 'btn_download') {
            // 跳转下载
        } else if (target.name == 'btn_arrest') {

             ////beak repair
             if (!playable.isInduce) {
                playable.install()
            } else {
                playable.install(InstallType.Induce)
            }
            if (this.ClickState) return
            this.ClickState = true
            playable.sendAction(6)
            // 结束事件
            playable.showEnding(true)

            // if(this.ClickState)return
            // this.ClickState = true
            // // 逮捕
            // playable.install(InstallType.Induce)
            // playable.sendAction(6)
            // // globalThis.mvPlayable  EventTypeObject
            // // 结束事件
            // playable.showEnding(true)
            // // this.eventSystem.dispatch(Playable.EndGameEvent);
        }
    }
    // 跳转状态
    JumpToState() {
        if (this.ClickScreen == 1) {
            // 首次点击埋点
            playable.sendAction(1)
        }
         ////beak repair
         if (gameConfig.config != 0 && this.ClickScreen % gameConfig.config == 0) {
            // 点击4次全局跳转
            if (playable.isInduce) {
                playable.install(InstallType.Induce)
            }
        }

        // if (this.ClickScreen == gameConfig.config) {
        //     // 点击4次全局跳转
        //     playable.install(InstallType.Global)
        //     // this.ClickScreen = 0
        // }

    }
    update(deltaTime: number) {

    }

    hideView() {
        this.node.active = false;
    }

    showView() {
        this.node.active = true;
    }
}


